package com.dlm.controller;

import com.dlm.dao.Technician;
import com.dlm.service.ITechnicianService;
import com.dlm.service.impl.TechnicianServiceImpl;
import com.dlm.util.GeomUtil;
import com.dlm.util.TypeUtil;
import com.google.common.base.Preconditions;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.vividsolutions.jts.io.WKBWriter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

/**
 * Created by chongsong on 15/2/1.
 * <mailto>chong.song@autonavi.com</mailto>
 */
public class TechnicianController extends BaseController{
    private Logger logger = Logger.getLogger(TechnicianController.class);
    private ITechnicianService service = new TechnicianServiceImpl();

    @Before(POST.class)
    public void add() {
        UploadFile uploadFile = getFile();
        String name = getPara("name");
        String headImg = getPara("headImg");
        String desc = getPara("desc");
        String address = getPara("address");
        int type = getParaToInt("type", 0);
        long tel = getParaToLong("tel", 0L);
        String phone = getPara("phone");
        int workEnd = getParaToInt("workEnd", 1);
        int workStart = getParaToInt("workStart", 1);
//        String posX = getPara("posX");
//        String posY = getPara("posY");
//        String city = getPara("city");

        headImg = "111";
        String city = "北京";
        String posX = "121.311338";
        String posY = "31.130064";
        try {
            Preconditions.checkArgument(StringUtils.isNotBlank(name), "name不能为空!");
//            Preconditions.checkArgument(StringUtils.isNotBlank(headImg), "headImg不能为空!");
            Preconditions.checkArgument(StringUtils.isNotBlank(desc), "desc不能为空!");
            Preconditions.checkArgument(StringUtils.isNotBlank(city), "city不能为空!");
            Preconditions.checkArgument(StringUtils.isNotBlank(address), "address不能为空!");
            Preconditions.checkArgument(TypeUtil.isDouble(posX), "posX不能为空,且必须为数字!");
            Preconditions.checkArgument(TypeUtil.isDouble(posY), "posY不能为空,且必须为数字!");
            Preconditions.checkArgument((type == 0 || type == 1), "type不能为空,且只能为0或者1!");
            Preconditions.checkArgument((workStart>=0 && workStart<=23), "workStart:工作开始时间不能为空,且只能0到23!");
            Preconditions.checkArgument((workEnd>=0 && workEnd<=23), "workEnd:工作结束时间不能为空,且只能0到23!");
            Preconditions.checkArgument((workEnd >= workStart), "工作结束时间必须大于工作开始时间!");
            Preconditions.checkArgument( tel > 0, "tel: 手机号必须输入!");
            Preconditions.checkArgument(StringUtils.isNotBlank(phone), "phone: 固定电话必须输入!");
        } catch (Exception e) {
            renderJson(makeDto(1,e.getMessage(),null));
            return;
        }
        boolean isSave = false;
        try {
            Technician tech = new Technician();
            tech.set(Technician.name,name);
            tech.set(Technician.headImg,headImg);
            tech.set(Technician.city,city);
            tech.set(Technician.address,address);
            tech.set(Technician.desc,desc);
            tech.set(Technician.type,type);
            tech.set(Technician.workEnd,workEnd);
            tech.set(Technician.workStart,workStart);
            tech.set(Technician.tel,tel);
            tech.set(Technician.phone,phone);
            if(uploadFile != null) {
                tech.set(Technician.headImg, "/upload/" + uploadFile.getFileName());
//                String saveDirectory = uploadFile.getSaveDirectory();
//                String contextPath = getSession().getServletContext().getRealPath("/");
//                String path = contextPath + "/upload/" + System.currentTimeMillis() + "_" + uploadFile.getFileName();
//                File file = new File(path);
//                FileOutputStream fos = new FileOutputStream(file);
//                FileUtils.copyFile(uploadFile.getFile(), fos);
//                fos.close();
            }
            isSave = service.add(tech);
            if(isSave){
                boolean flag = service.updatePos(TypeUtil.toDouble(posX),TypeUtil.toDouble(posY),tech.getInt("id"));
                if(flag){
                    renderJson(makeDto(0, "成功!", null));
                    return;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        renderJson(makeDto(1, "保存失败!", null));
    }

    public void del(){
        long id = getParaToLong("id", 0l);
        try {
            Preconditions.checkArgument(id > 0, "id不能为空且必须大于0!");
        } catch (Exception e) {
            renderJson(makeDto(1,e.getMessage(),null));
            return;
        }
        boolean isDel = false;
        try {
            isDel = service.delete(id);
            if(isDel){
                renderJson(makeDto(0,"ok",null));
                return;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        renderJson(makeDto(1,"删除失败",null));
    }

    public void find(){
        int pno = getParaToInt("pno",1);
        if(pno <= 0){
            pno = 1;
        }
        int psize = getParaToInt("psize",10);
        long itemId = getParaToInt("itemId",-1);
        String posX = getPara("posX");
        String posY = getPara("posY");
        //TODO 设置city
        String city = getPara("city");
        //TODO 暂时写死到七宝.
        posX = "121.361238";
        posY = "31.159064";
        try {
            Preconditions.checkArgument(TypeUtil.isDouble(posX), "posX:经度不能为空,且必须为数字!");
            Preconditions.checkArgument(TypeUtil.isDouble(posY), "posY:维度不能为空,且必须为数字!");
        } catch (Exception e) {
            renderJson(makeDto(1,e.getMessage(),null));
            return;
        }
        try {
            Page<Technician> page = service.findByPage(itemId,TypeUtil.toDouble(posX),TypeUtil.toDouble(posY),pno, psize);
            renderJson(makeDtoPage(0,"ok",page));
            return;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        renderJson(makeDto(1,"查询失败",null));
    }

    public void findById(){
        long techId = getParaToLong("id", 0L);
        try{
            Preconditions.checkArgument((techId>0), "id必须为正整数!");
        }catch (Exception e){
            renderJson(makeDto(1,e.getMessage(),null));
            return;
        }
        try {
            Technician tech = service.findById(techId);
            if(tech == null) {
                throw new Exception("该技师不存在! id:"+techId);
            }
            renderJson(makeDto(0,"ok",tech));
        } catch (Exception e) {
            renderJson(makeDto(1, e.getMessage(), null));
        }
    }

    public void findWT(){
        String date = getPara("date");
        String time = getPara("time");

        String posX = getPara("posX");
        String posY = getPara("posY");
        //TODO 设置city
        String city = getPara("city");
        //TODO 暂时写死到七宝.
        posX = "121.361238";
        posY = "31.159064";

        try{
            Preconditions.checkArgument(TypeUtil.isDouble(posX), "posX:经度不能为空,且必须为数字!");
            Preconditions.checkArgument(TypeUtil.isDouble(posY), "posY:维度不能为空,且必须为数字!");
            Preconditions.checkArgument(StringUtils.isNotBlank(date), "date不能为空!");
            Preconditions.checkArgument(StringUtils.isNotBlank(time), "time不能为空!");
            List<Technician> wt = service.findWT(TypeUtil.toDouble(posX),TypeUtil.toDouble(posY),date, time);
            if(wt == null) {
                throw new Exception("查询失败! ");
            }
            renderJson(makeDtoList(0, "ok",wt));
        }catch (Exception e){
            renderJson(makeDto(1,e.getMessage(),null));
        }
    }
}
